"""
    :Views: Defining the views function
    :Author: MiaLi
"""
from flask import flash, redirect, url_for, render_template

from messageboard import app, db
from messageboard.forms import MessageForm
from messageboard.models import Message


@app.route('/', methods=['GET', 'POST'])
def index():
    form = MessageForm()
    if form.validate_on_submit():
        name = form.name.data
        body = form.body.data
        message = Message(name=name, body=body)
        db.session.add(message)
        db.session.commit()
        flash('您的留言已被发布。')
        return redirect(url_for('index'))
    sql = db.select(Message).order_by(Message.timestamp.desc())
    messages = db.session.execute(sql).scalars().all()
    return render_template('index.html', messages=messages, form=form)
